<script setup lang="jsx">
import { ref } from 'vue'
import TableLayout from '@/components/TableLayout.vue'
import TopFilter from '@/components/CRUD/TopFilter.vue'
import TableCard from '@/components/TableCard/index.vue'
import CompanySelect from '@/views/PropertyCompany/components/CompanySelect.vue'
import CommunitySelect from '@/views/PropertyCompany/components/CommunitySelect.vue'
import MyUpload from '@/components/MyUpload.vue'
import { useTable, useFilters } from '@/hooks'
import ElMoney from '@/components/ElMoney.vue'

import { RecordModel, CaseModel, RecyclingModel, MessageModel, RepostModel, TreaModel, LawyerModel, ReduceAmount } from './components/index'

import { getArrearsList, importArrearsData, exportArrearsData, getArrearsSummary, importUpdateArrearsData, checkImport, triggerLitigation, arrearsTraceServer, triggerArrearsClosed } from '@/api/arrears'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'


const filters = [
  { key: 'keyword', type: 'input', props: { placeholder: '请输入姓名、电话或房间号' } },
  {
    key: 'case_reason',
    type: 'select',
    props: { placeholder: '请选择欠费类型' },
    options: [{ value: '物业费', label: '物业费' }, { value: '供暖费', label: '供暖费' }, { value: '其他', label: '其他' }]
  },
  {
    key: 'status',
    type: 'select',
    props: { placeholder: '请选择收回状态' },
    options: [{ value: '已收回', label: '已收回' }, { value: '部分收回', label: '部分收回' }, { value: '未收回', label: '未收回' }]
  },
  {
    key: 'is_split',
    type: 'select',
    props: { placeholder: '请选择断缴状态' },
    options: [{ value: false, label: '未断缴' }, { value: true, label: '已断缴' }]
  },
  {
    key: 'is_litigation',
    type: 'select',
    props: { placeholder: '请选择是否诉讼' },
    options: [{ value: true, label: '是' }, { value: false, label: '否' }]
  },
]

const userStore = useUserStore()

const companyId = ref()
const communityId = ref()
const { params, getParams } = useFilters(filters)
const { page_num, size, total, tableData, getData, loading } = useTable(getArrearsList)
const getTableData = (keepPage) => {
  if (!keepPage) page_num.value = 1
  getData({
    company_id: companyId.value,
    community_id: communityId.value,
    ...getParams()
  })
}

// 摘要
const summary = ref({
  sum_has_pay_amount: 0, // 已支付金额
  sum_last_amount: 0, // 总剩余金额
  row_count: 0, // 行数
  sum_amount: 0, // 总金额
})
const getSummary = async () => {
  if (!communityId.value) return;
  const { data } = await getArrearsSummary({
    page_num: page_num.value,
    size: size.value,
    company_id: companyId.value,
    community_id: communityId.value,
  });
  summary.value = data || {}
}

const initPage = (keepPage) => {
  getTableData(keepPage);
  getSummary();
}
initPage();

const tableRef = ref(null) // 表格组件引用
const isSelectedAll = ref(false) // 全选状态
const isIndeterminate = ref(false) // 是否为半选状态
let selectedRows = []
const onSelection = (rows) => {
  const selectableLen = tableData.value.filter(selectable).length; // 可选择的行数
  isSelectedAll.value = selectableLen !== 0 && rows.length === selectableLen; // 如果选中的行数等于总行数，则全选
  isIndeterminate.value = rows.length > 0 && rows.length < selectableLen; // 如果选中的行数大于0且小于总行数，则为半选状态
  selectedRows = rows;
}
const onTriggerSelectAll = () => {
  tableRef.value.onTriggerSelectAll(isSelectedAll.value);
}
const selectable = row => !row.is_litigation && !row.is_withdraw // 选择行的条件，未诉讼且未撤回的数据可以被选择

// 导入新数据，需要检查数据
const onAddImport = async (files) => {
  const tempFile = files[0];
  const { data } = await checkImport({ file: tempFile });
  if (data?.error_messages?.length) {
    ElMessage.error(data.error_messages.join(', '));
    return;
  }
  const checkData = data.group_data
  await ElMessageBox.confirm(
    <>
      <span>户数：{checkData['户数'] || 0}</span><br />
      <span>总金额：<ElMoney num={checkData['总金额'] || 0} /></span><br />
      <span>行数：{checkData['行数'] || 0}</span>
    </>,
    '请确认数据', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })

  await importArrearsData({
    company_id: companyId.value,
    community_id: communityId.value,
    file: tempFile,
  });
  ElMessage.success('导入数据成功');
  initPage();
}

// 导出数据
const onExport = async () => {
  const { data } = await exportArrearsData({
    company_id: companyId.value,
    community_id: communityId.value,
    ...getParams(),
  });
  const url = data?.url
  const link = document.createElement('a');
  link.href = url;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  ElMessage.success('导出成功');
}
// 导入修改数据
const onUpdateImport = async (files) => {
  await importUpdateArrearsData({
    company_id: companyId.value,
    community_id: communityId.value,
    file: files[0],
  });
  ElMessage.success('修改数据成功');
  initPage();
}

const info = ref()
const infoList = ref([])

// 案件文书
const isCase = ref(false)
const onCaseFiles = (row) => {
  isCase.value = true;
  info.value = row;
}

// 生成起诉状
const isTrea = ref(false)
const onCreateTrea = (row) => {
  isTrea.value = true;
  info.value = row;
}

// 转诉讼
const onLitigation = async (row) => {
  await ElMessageBox.confirm(`是否确认转诉讼？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
  await triggerLitigation({
    arrears_data_id: row.arrears_data_id,
  })
  ElMessage.success('转诉讼成功');
  getTableData(true);
}

// 取消/收藏跟进记录
const onStar = async (row, trace) => {
  await arrearsTraceServer.put({
    trace_id: trace.trace_id,
  })
  if (trace.is_star) {
    ElMessage.success('取消收藏成功');
  } else {
    ElMessage.success('收藏成功');
  }
  getTableData(true);
}

// 转跟案律师
const isRepost = ref(false)
const onChangeLawyer = (row) => {
  infoList.value = [row];
  isRepost.value = true
}
const onBatchChangeLawyer = () => {
  if (selectedRows.length === 0) {
    ElMessage.warning('请先选择需要批量分配的数据');
    return;
  }
  infoList.value = selectedRows;
  isRepost.value = true
}

// 撤回/取消撤回数据
const onTriggerCancelData = async (row) => {
  const title = row.is_withdraw ? '取消撤回' : '撤回';
  await ElMessageBox.confirm(`是否确认${title}数据？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
  await triggerArrearsClosed({
    arrears_data_id: row.arrears_data_id,
  })
  ElMessage.success(title + '成功');
  initPage(true);
}

// 批量生成律师函
const isLawyer = ref(false);
const onBatchCreateLetter = () => {
  if (selectedRows.length === 0) {
    ElMessage.warning('请先选择需要批量生成律师函的数据');
    return;
  }
  const reason = selectedRows[0].case_reason;
  if (selectedRows.some(row => row.case_reason !== reason)) {
    ElMessage.warning('生成律师函的数据必须是同一欠费类型，请检查后重试');
    return;
  }
  infoList.value = selectedRows;
  isLawyer.value = true
}

// 减免金额
const isReducing = ref(false)
const onReduceAmount = (row) => {
  info.value = row;
  isReducing.value = true;
}

// 回收
const isRecycling = ref(false)
function handleRecycling(row) {
  isRecycling.value = true
  info.value = row
}

// 查看跟进记录
const isRecord = ref(false)
function onCheckRecord(row) {
  isRecord.value = true
  info.value = row
}

// 批量发送短信
const isMessage = ref(false)
const onBatchSendMessage = () => {
  if (selectedRows.length === 0) {
    ElMessage.warning('请先选择需要批量发送短信的数据');
    return;
  }
  infoList.value = selectedRows;
  isMessage.value = true
}

</script>
<template>
  <div class="w-full h-full flex flex-col">
    <div class="flex items-center justify-between mb-4 h-16">
      <div class="flex gap-4">
        <CompanySelect v-model="companyId" placeholder="请选择物业公司" @change="initPage()" />
        <CommunitySelect v-model="communityId" :companyId="companyId" @change="initPage()" placeholder="请选择项目" />
      </div>
      <div class="flex items-center text-xs text-zinc-500 gap-3" v-if="communityId">
        <span>总户数:{{ summary.row_count || 0 }}</span>
        <span>总欠费金额：<el-money :num="summary.sum_amount || 0" /></span>
        <span>未收回金额：<el-money :num="summary.sum_last_amount || 0" /></span>
        <span>已收回金额：<el-money :num="summary.sum_has_pay_amount || 0" /></span>
        <div class="progress" style="--el-fill-color-light: #fff">
          <el-progress type="circle" :width="56" :stroke-width="4"
            :percentage="summary.sum_amount ? Number((100 * summary.sum_has_pay_amount / summary.sum_amount).toFixed(2)) : 0" />
        </div>
      </div>
    </div>
    <TableLayout class="full-page flex-1 overflow-hidden" v-model:page="page_num" v-model:size="size" :total="total"
      @table-change="getTableData">
      <template #header>
        <div class="flex items-center justify-between">
          <el-checkbox v-model="isSelectedAll" :indeterminate="isIndeterminate"
            @change="onTriggerSelectAll">全选</el-checkbox>
          <TopFilter class="flex-1 flex-wrap ml-4" :model="params" :filters="filters" @change="getTableData()" />
          <div class="flex items-center">
            <el-button :disabled="!communityId" type="primary" @click="onExport()">导出数据</el-button>
            <MyUpload :disabled="!communityId" accept=".xls,.xlsx" @change="onUpdateImport">
              <el-button class="mx-3" type="primary" :disabled="!communityId">批量修改</el-button>
            </MyUpload>
            <el-button v-if="userStore.userInfo?.is_arrears_manager" type="primary"
              @click="onBatchChangeLawyer()">批量分配数据</el-button>
            <el-button type="primary" @click="onBatchSendMessage()">批量发送短信</el-button>
            <el-button type="primary" :disabled="!communityId" @click="onBatchCreateLetter()">批量生成律师函</el-button>
            <MyUpload :disabled="!communityId" accept=".xls,.xlsx" @change="onAddImport">
              <el-button class="ml-3" type="primary" :disabled="!communityId">导入数据</el-button>
            </MyUpload>
          </div>
        </div>
      </template>
      <template #table>
        <TableCard ref="tableRef" :tableData="tableData" v-loading="loading" id-key="arrears_data_id" selection
          @select-change="onSelection" @star="onStar" @cardClick="onCheckRecord" :selectable="selectable">
          <template #handler="{ row }">
            <div class="flex items-center">
              <el-button v-if="row.is_withdraw" type="primary" size="small" text
                @click="onTriggerCancelData(row)">取消撤回</el-button>
              <template v-else>
                <el-button v-if="row.status !== '已收回'" type="primary" size="small" text
                  @click="handleRecycling(row)">收回</el-button>
                <span v-else>已收回</span>
                <el-dropdown trigger="click">
                  <el-button class="ml-2" type="primary" size="small" text>更多</el-button>
                  <template #dropdown>
                    <el-dropdown trigger="click">
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click="onCaseFiles(row)">案件文书</el-dropdown-item>
                        <template v-if="row.status !== '已收回'">
                          <el-dropdown-item @click="onCreateTrea(row)">生成起诉状</el-dropdown-item>
                          <el-dropdown-item v-if="!row.is_litigation" @click="onLitigation(row)">转诉讼</el-dropdown-item>
                          <el-dropdown-item @click="onChangeLawyer(row)">转跟案律师</el-dropdown-item>
                          <el-dropdown-item @click="onTriggerCancelData(row)">撤回数据</el-dropdown-item>
                          <el-dropdown-item @click="onReduceAmount(row)">减免金额</el-dropdown-item>
                        </template>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </el-dropdown>
              </template>
            </div>
          </template>
        </TableCard>
      </template>
    </TableLayout>

    <!-- 案件文书 -->
    <el-dialog v-model="isCase" title="案件文书" width="65%" destroy-on-close>
      <CaseModel :info="info" />
    </el-dialog>

    <!-- 生成起诉状 -->
    <el-dialog v-model="isTrea" title="生成起诉状" width="50%" destroy-on-close>
      <TreaModel :info="info" @close="isTrea = false" @success="getTableData(true)" />
    </el-dialog>

    <!-- 转跟案律师 -->
    <el-dialog v-model="isRepost" :title="infoList.length > 1 ? '批量转跟案' : '转跟案律师'" width="50%" destroy-on-close>
      <RepostModel :infoList="infoList" @success="getTableData(true)" @close="isRepost = false" />
    </el-dialog>

    <!-- 批量生成律师函 -->
    <el-dialog v-model="isLawyer" title="批量生成律师函" width="50%" destroy-on-close>
      <LawyerModel :infoList="infoList" :companyId="companyId" :communityId="communityId" @success="getTableData(true)"
        @close="isLawyer = false" />
    </el-dialog>

    <!-- 减免金额 -->
    <el-dialog v-model="isReducing" title="减免金额" width="50%" destroy-on-close>
      <ReduceAmount :info="info" @close="isReducing = false" @success="getTableData(true)" />
    </el-dialog>

    <!-- 收回 -->
    <el-dialog v-model="isRecycling" title="收回" width="50%" destroy-on-close>
      <RecyclingModel :info="info" @close="isRecycling = false" @success="getTableData(true)" />
    </el-dialog>

    <!-- 跟进数据 -->
    <el-drawer v-model="isRecord" title="跟进记录" width="500px" destroy-on-close>
      <RecordModel :info="info" @success="getTableData(true)" />
    </el-drawer>

    <!-- 批量发送短信 -->
    <el-dialog v-model="isMessage" title="批量发送短信" width="50%" destroy-on-close>
      <MessageModel :infoList="infoList" @success="getTableData(true)" @close="isMessage = false" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.progress {
  :deep(.el-progress__text) {
    min-width: auto;
    font-size: 12px !important;
  }
}
</style>